package demo2;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 使用NIO完成网络通信的三个核心
 *
 * 一：通道，主要负责连接
 * 二：缓冲区 负责数据的存取
 * 三：选择器 是SelectableChannel的多路复用器，用于监控SelectableChannel的一些状况
 */
public class TestBlockingIO {

    @Test
    public void client() throws IOException {
        /**
         * 开启通道
         */
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8080));

        /**
         * 分配指定大小的缓冲区
         */
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        /**
         * 读取本地文件并发送到服务端去
         */
        FileChannel fileChannel = FileChannel.open(Paths.get("D:\\1\\2.jpg"), StandardOpenOption.READ);
        while (fileChannel.read(buffer)!=-1){
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        fileChannel.close();
        socketChannel.close();
    }
    @Test
    public void server() throws IOException {
        /**
         * 获取通道
         */
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        /**
         * 绑定端口号
         */
        serverSocketChannel.bind(new InetSocketAddress(8080));

        /**
         * 获取客户端的连接通道
         */
        SocketChannel accept = serverSocketChannel.accept();
        /**
         * 接收客户端的数据
         */
        FileChannel fileChannel = FileChannel.open(Paths.get("D:\\1\\1.jpg"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (accept.read(byteBuffer)!=-1){
            byteBuffer.flip();
            fileChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        accept.close();
        fileChannel.close();
        serverSocketChannel.close();

    }
}
